﻿namespace Probel.Statistics
{
    using System;
    using System.Linq;

    using Probel.Statistics.Domain;
    using Probel.Statistics.Helpers;

    public class StatLogger : IStatLogger
    {

        #region Methods

        public void ClearStatistics()
        {
            using (var db = new DataContext())
            {
                db.Applications.RemoveRange(db.Applications);
                db.SaveChanges();
            }
        }

        public void Register(string serial, string version, string application)
        {
            using (var db = new DataContext())
            {
                var now = DateTime.UtcNow;

                var registeredApp = (from app in db.Applications
                                     where app.WindowsSerial == serial
                                        && app.AppName == application
                                     select app).FirstOrDefault();

                if (registeredApp == null)
                {
                    var entity = new Application()
                    {
                        AppName = application,
                        WindowsVersion = version.ToCommercialVersion(),
                        WindowsSerial = serial,
                        RegistrationDate = now,
                        LastConnection = now
                    };
                    db.Applications.Add(entity);
                }
                else
                {
                    registeredApp.Counter++;
                    registeredApp.LastConnection = now;
                }

                db.SaveChanges();
            }
        }

        #endregion Methods
    }
}